import { request } from "../utils"
import { wxAppId } from "../config/global"
import { getQueryString, filterEmoji } from '../utils'
import { getShareUrl } from '../utils/share'
import { getWechatSign, registerUser, getBindInfo } from "../network/user" // 获取微信配置信息网络请求、注册登录用户
import wx from "weixin-js-sdk"
import { Toast } from 'vant'
const {
  EVN,
  productionDomain,
  natDomain,
} = require("../config/global.js")

/**
 * 获取微信code
 * 注：访问网址必须未经过encodeURIComponent
 * 返回code[promise]
 */
const getWxCode = (from) => {
  return new Promise((resolve, reject) => {
    let code = getQueryString('code')
    // 如果不存在code，则通过微信授权获取
    if(!code){
      let redirectUrl = location.href
      let snsapi = getWxSnsapi(wxAppId, redirectUrl, from)
      setTimeout(() => {
        location.href = snsapi
      }, 1000);
    } else 
    // 存在code，则返回code用于获取openid
    {
      resolve(code)
    }
  })
}

/**
 * 微信授权获取code，根据code获取openid
 */
const getOpenId = async (from) => {
  let code = await getWxCode(from)
  return new Promise((resolve) => {
    request({
      url: "api/Wx/GetUser",
      params: { code },
    }).then((res) => {
      if (res.data.Success) {
        let wxInfo = res.data.Data
        wxInfo.nickname = filterEmoji(wxInfo.nickname) // 去除微信昵称中的表情符号
        localStorage.setItem("wxInfo", JSON.stringify(wxInfo))
        resolve(wxInfo.openid)
      } else {
        console.log("获取微信用户信息失败...")
      }
    })
  })
}

/**
 * 获取微信授权中间跳转地址
 * @param {*} appid 公众号appid
 * @param {*} redirectUrl 授权后回跳页面地址
 * 返回授权跳转地址
 */
const getWxSnsapi = (appid, redirectUrl, from) => {
  if(from === 'entry'){
    let shareUserId = getQueryString("shareUserId")
    let shareUserIdStr = shareUserId ? "?shareUserId=" + shareUserId : ""

    redirectUrl =
      EVN === "development"
        ? `${natDomain}${shareUserIdStr}#/loginauto`
        : `${productionDomain}Images/dist/${shareUserIdStr}#/loginauto`
    
  }
  
  let snsapi =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    encodeURIComponent(redirectUrl) +
    "&response_type=code&scope=snsapi_userinfo"
  return snsapi
}

/**
 * 微信jsApi配置
 * @param {*} config 微信sdk配置参数
 * @param {*} jsApiList 需要使用的JS接口列表
 */
const wxConfig = () => {
  getWxSign().then(config => {
    wx.config({
      debug: false,
      appId: config.wxAppId, // 必填，公众号的唯一标识
      timestamp: config.timestamp, // 必填，生成签名的时间戳
      nonceStr: config.nonceStr, // 必填，生成签名的随机串
      signature: config.signature, // 必填，签名
      jsApiList: [
        "getLocation",
        "chooseWXPay",
        "updateAppMessageShareData",
        "updateTimelineShareData",
      ]
    })
  })
}

/**
 * 用户分享
 * @param {*} options
 * {
 *  title: 
 *  desc: 
 *  link: 
 *  imgUrl: 
 *  success: 
 * }
 */
const sharePage = async (options) => {
  options = options ? options : {}
  options.title = options.title || "titikaactive官方店" // 分享标题
  options.desc = options.desc || "来自加拿大的专业瑜伽品牌" // 分享描述
  options.link = options.link || await getShareUrl() // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  options.imgUrl = options.imgUrl || "http://shop.jdpin.com.cn/Storage/template/0/20200528/6372626998340372232242449.png" // 分享图标
  options.success = options.success || null

  let friendOptions = {
    title: options.title,
    link: options.link,
    imgUrl: options.imgUrl,
    success: options.success,
  }

  wx.ready(() => {
    wx.updateAppMessageShareData(options)
    wx.updateTimelineShareData(friendOptions)
  })
}

/**
 * 获取微信sdk配置参数
 * 注：访问网址需不需要经过encodeURIComponent
 *    根据后端实际情况
 * 返回配置参数[promise]
 */
const getWxSign = () => {
  return new Promise((resolve, reject) => {
    let url = location.href.split("#")[0]
    getWechatSign({
      url
    }, config => {
      resolve(config)
    })
  })
}

/**
 * 使用openid登录应用
 */
const loginWithOpenId = async (vm, from) => {
  await getOpenId(from)
  let wxInfo = JSON.parse(localStorage.getItem("wxInfo"))
  let isBind = await toGetBindInfo(wxInfo)
  
  // 未绑定过用户 微信和手机号绑定
  if(!isBind){
    vm.$router.push("/login")
    return false
  }

  // 已绑定过用户 微信登录
  let requestData = {
    userName: '',
    password: '',
    code: '',
    mobile: '',
    parnetId: getQueryString('shareUserId') || 0,

    oauthNickName: wxInfo.nickname,
    oauthType: 'Himall.Plugin.OAuth.WeiXin',
    oauthOpenId: wxInfo.openid,
    unionid: wxInfo.unionid,
    sex: wxInfo.sex,
    headimgurl: wxInfo.headimgurl,
  }
  // 调用登录
  registerUser(vm, requestData, () => {
    if (sessionStorage.getItem("goAfterLogin") === "coupon") {
      vm.$router.push({
        path: "/coupon",
        query: {
          id: sessionStorage.getItem("shareCoupons"),
        },
      })
    } else {
      vm.$router.push("/best")
    }
  })
}

function toGetBindInfo(wxInfo){
  return new Promise(resolve => {
    let requestData = {
      par: wxInfo.openid,
    }
    getBindInfo(requestData, (res) => {
      resolve(res)
    })
  })
}

/**
 * 用户登录
 * @param {*} vm page当中的this
 */
const multLogin = (vm) => {
  return new Promise((resolve, reject) => {
    // 用户未登录状态下，适配多种登录方案
    if(!localStorage.getItem('userKey')){
      // 微信端，code获取openid自动登录
      initToEntry()
      resolve(false)
    } else {
      resolve(true)
    }
  })
}

/*
  跳转到主界面
*/
const initToEntry = () => {
  let shareUserId = getQueryString("shareUserId")
  let shareUserIdStr = shareUserId ? "?shareUserId=" + shareUserId : ""

  setTimeout(() => {
    localStorage.removeItem("wxLoginClicked")
    location.href =
      EVN === "development"
        ? `${natDomain}${shareUserIdStr}#/entry`
        : `${productionDomain}Images/dist/${shareUserIdStr}#/entry`
  }, 1000)
}

export { 
  loginWithOpenId, 
  multLogin, 
  wxConfig, 
  sharePage, 
}